layui.use(['layer', 'form', 'table', 'util', 'admin', 'element', 'laydate', 'jquery', 'dropdown', 'xmSelect', 'treeTable'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var admin = layui.admin;
    var element = layui.element;
    var laydate = layui.laydate;
    var dropdown = layui.dropdown;
    var xmSelect = layui.xmSelect;
    var treeTable = layui.treeTable;


    //渲染日期组件
    renderLayDateCp($, laydate);


    //渲染表格
    var roleInsTb = table.render({
        elem: '#roleTable',
        url: prefix + '/list',
        page: true,
        toolbar: ['<p>',
            '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn ' + addFlag + '"><i class="layui-icon layui-icon-addition"></i>添加</button>&nbsp;',
            '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn ' + removeFlag + '"><i class="layui-icon layui-icon-delete"></i>删除</button>&nbsp;',
            '<button lay-event="export" class="layui-btn layui-btn-sm layui-bg-cyan icon-btn ' + exportFlag + '"><i class="layui-icon layui-icon-export"></i>导出</button>',
            '</p>'].join(''),
        initSort: {
            field: 'gmtCreate'
            , type: 'desc'
        },
        where: {
            fieldName: 'gmtCreate'
            , sortType: 'desc'
        },
        cols: [
            [
                {type: 'checkbox'},
                {field: 'roleId', title: '角色ID', sort: true},
                {field: 'roleName', title: '角色名称', sort: true},
                {field: 'roleKey', title: '权限标识', sort: true},
                {field: 'roleSort', title: '显示顺序', sort: true},
                {
                    field: 'status', title: '角色状态', templet: function (d) {
                        return showDictLabel(dictSysNormalDisable, d.status);
                    }, sort: true
                },
                {
                    field: 'gmtCreate', title: '创建时间', templet: function (d) {
                        return util.toDateString(d.gmtCreate);
                    }, sort: true
                },
                {title: '操作', toolbar: '#roleTbBar', align: 'center', minWidth: 250}
            ]
        ]
        , done: function (res, curr, count) {
            //导出的下拉菜单
            dropdown.render({
                elem: 'button[lay-event=export]'
                , trigger: 'hover'
                , data: [{
                    title: '导出全部（无过滤）'
                    , id: "exportAll"
                }, {
                    title: '导出全部（过滤搜索）'
                    , id: "exportSearch"
                }, {
                    title: '导出当前页数据'
                    , id: "exportCurrent"
                }]
                , click: function (obj) {
                    var id = obj.id;
                    if (id === "exportSearch") {
                        var data = $("#dictDataTbSearchForm").serializeArray();
                        exportExcel(data);
                    } else if (id === "exportAll") {
                        exportExcel({});
                    } else {
                        exportExcelCurrent(table, res.data);
                    }
                }
            });
        }
    });


//表格搜索
    form.on('submit(roleTbSearch)', function (data) {
        if (data.field.gmtCreate) {
            var sbt1 = data.field.gmtCreate.split('~');
            data.field.searchParams[gmtCreateStart] = sbt1[0];
            data.field.searchParams[gmtCreateEnd] = sbt1[1];
            data.field.gmtCreate = undefined;
        }
        roleInsTb.reload({where: data.field, page: {curr: 1}});
        return false;
    });


//表头工具栏点击事件
    table.on('toolbar(roleTable)', function (obj) {
        var data = table.checkStatus('roleTable').data;
        if (obj.event === "add") {
            showEditModel();
        } else if (obj.event === "del") {
            data = data.map(function (item) {
                return item.roleId;
            });
            deleteData(data);
        }
    });


//表格工具条点击事件
    table.on('tool(roleTable)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            deleteData([data.roleId]);
        } else if (obj.event === 'edit') {
            showEditModel(data);
        }
    });

//触发排序事件
    table.on('sort(roleTable)', function (obj) {
        roleInsTb.reload({
            initSort: obj
            , where: {
                fieldName: obj.field
                , sortType: obj.type
            }
        });
    });

//编辑或添加
    function showEditModel(mData) {
        admin.open({
            type: 1,
            area: '550px',
            title: (mData ? '修改' : '添加') + '角色信息',
            content: $('#roleEditDialog').html(),
            success: function (layero, dIndex) {
                form.render();
                if (mData) {
                    // 回显表单数据
                    form.val('roleEditForm', mData);
                }
                // 表单提交事件
                form.on('submit(roleEditSubmit)', function (data) {
                    renderLayDateCp($, laydate);
                    var loadIndex = layer.load(2);
                    //包含半勾选的
                    var menuTreeValue = menuSel.getTreeValue(false, true);
                    //不包含半勾选的
                    var dsTreeValue = dataScopeInsSel.getTreeValue(false, false);
                    //xmSelect的知道的表单提交目前只能提交叶子节点，所以此处需要手动获取全部节点
                    data.field.menuIds = menuTreeValue ? menuTreeValue.map(function (item, index) {
                        return item.id;
                    }).join(",") : "";
                    data.field.deptIds = dsTreeValue ? dsTreeValue.map(function (item, index) {
                        return item.id;
                    }).join(",") : "";
                    admin.req(prefix + (mData ? '/edit' : '/add'), data.field, function (resp) {
                        layer.close(loadIndex);
                        if (resp.code === 0) {
                            layer.close(dIndex);
                            himio.notice.success(resp.msg);
                            roleInsTb.reload({page: {curr: 1}});
                        } else {
                            himio.notice.error(resp.msg);
                        }
                    }, 'post');
                    return false;
                });

                // 渲染菜单树下拉树
                var menuSel = xmSelect.render({
                    el: '#menuSel',
                    height: '250px',
                    autoRow: true,
                    //不能用此处的自带的表单提交，因为只会提交叶子节点，父节点不会提交）
                    // name: 'menuIds',
                    layVerify: 'required',
                    layVerType: 'tips',
                    filterable: true,
                    tree: {
                        show: true,
                        showFolderIcon: true,
                        indent: 15,
                        strict: true,
                        simple: true,
                        expandedKeys: true
                    },
                    toolbar: {
                        show: true,
                        list: ['ALL', 'REVERSE', 'CLEAR', {
                            name: '展开全部',
                            icon: 'fa fa-plus-square-o',
                            method: function (data) {
                                menuSel.changeExpandedKeys(true)
                            }
                        }, {
                            name: '关闭全部',
                            icon: 'fa fa-minus-square-o',
                            method: function (data) {
                                menuSel.changeExpandedKeys(false)
                            }
                        }]
                    },
                    data: [],
                    prop: {
                        name: 'title',
                        value: 'id'
                    }
                });
                //更新菜单树数据
                admin.req(prefixMenu + (mData ? "/roleMenuTreeData" : "/menuTreeData"),
                    mData ? {roleId: mData.roleId} : {},
                    function (resp) {
                        var data = treeTable.pidToChildren(resp, 'id', 'pid');
                        //为什么这里要反复横跳（strict先false再true）
                        //先设置非严格模式勾选后台传过来的数据，防止半勾选影响子节点
                        //后面又设置回true，让编辑的时候可以由父子关系影响，从而简便操作
                        //此处应该是作者没有考虑到的，这里需要注意一下
                        menuSel.update({
                            data: data,
                            tree: {
                                strict: false
                            }
                        });
                        menuSel.update({
                            tree: {
                                strict: true
                            }
                        })
                        var expandIds = [];
                        for (var i = 0; i < resp.length; i++) {
                            if (resp[i].pid === 0) {
                                expandIds.push(resp[i].id);
                            }
                        }
                        //展开第一级菜单
                        menuSel.changeExpandedKeys(expandIds);
                    });

                //显隐部门数据下拉勾选组件
                var formData = form.val('roleEditForm');
                var dataScope = formData.dataScope;
                if (dataScope === "2") {
                    $("#dataScopeItem").removeClass("layui-hide");
                } else {
                    $("#dataScopeItem").addClass("layui-hide");
                }
                //渲染弹框中部门树（数据权限勾选）
                var dataScopeInsSel = xmSelect.render({
                    el: '#dataScopeDeptSel',
                    height: 'auto',
                    autoRow: true,
                    data: [],
                    //不能用此处的自带的表单提交，因为只会提交叶子节点，父节点不会提交）
                    // name: 'deptIds',
                    prop: {
                        name: 'title',
                        value: 'id'
                    },
                    filterable: true,
                    clickClose: true,
                    toolbar: {
                        show: true,
                        list: ['ALL', 'CLEAR', 'REVERSE']
                    },
                    tree: {
                        show: true,
                        showFolderIcon: true,
                        indent: 15,
                        strict: true,
                        simple: true,
                        expandedKeys: true
                    }

                });
                //更新数据权限部门树数据
                admin.req(prefixDept + (mData ? "/roleDeptTreeData" : "/roleTreeData"),
                    mData ? {roleId: mData.roleId} : {},
                    function (resp) {
                        var data = treeTable.pidToChildren(resp, 'id', 'pid');
                        //为什么这里要反复横跳（strict先false再true）
                        //先设置非严格模式勾选后台传过来的数据，防止半勾选影响子节点
                        //后面又设置回true，让编辑的时候可以由父子关系影响，从而简便操作
                        //此处应该是作者没有考虑到的，这里需要注意一下
                        dataScopeInsSel.update({
                            data: data,
                            tree: {strict: false}
                        });
                        dataScopeInsSel.update({tree: {strict: true}})
                        var expandIds = [];
                        for (var i = 0; i < resp.length; i++) {
                            if (resp[i].pid === 0) {
                                expandIds.push(resp[i].id);
                            }
                        }
                        //展开第一级菜单
                        dataScopeInsSel.changeExpandedKeys(expandIds);
                    });

                // 禁止弹窗出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }


    form.on('select(dataScope)', function (data) {
        if (data.value === "2") {
            $("#dataScopeItem").removeClass("layui-hide");
        } else {
            $("#dataScopeItem").addClass("layui-hide");
        }
    });


//删除
    function deleteData(data) {
        if (data.length === 0) {
            himio.notice.warn('请选择要删除的数据');
            return;
        }
        admin.confirm("确认要删除选中的" + data.length + "条数据吗?", function (index) {
            admin.req(prefix + "/remove", {
                ids: data.join(",")
            }, function (resp) {
                himio.notice.resp(resp, function () {
                    roleInsTb.reload({where: data.field, page: {curr: 1}});
                });
                layer.close(index);
            }, "post");
        });
    }

    /* 导出 excel 数据 */
    function exportExcel(data) {
        layer.confirm("确定导出所有角色信息数据吗？", function (index) {
            himio.notice.loading("正在导出数据，请稍后...");
            admin.req(prefix + "/export", data, function (result) {
                himio.notice.resp(result, function () {
                    layer.close(index);
                    window.location.href = ctx + "common/download?fileName=" + encodeURI(result.data) + "&delete=" + true;
                    notice.destroy();
                });
            }, "post");
        });
    }

    /* 导出当前页 excel 数据 */
    function exportExcelCurrent(table, exportData) {
        var title = [
            '角色名称',
            '角色权限字符串',
            '角色状态',
            '创建时间'
        ];
        var data = [];
        for (var i = 0; i < exportData.length; i++) {
            data.push([
                exportData[i].roleName,
                exportData[i].roleKey,
                exportData[i].status,
                exportData[i].gmtCreate
            ]);
        }
        table.exportFile(title, data, 'xls');
    }

});
